<!--
 * @Descripttion: (/EG_Feedback_List)
 * @Author: (admin)
 * @Date: (2025-11-26)
-->
<template>
  <div class="chat-container">
    <div class="chat-messages">
      <div 
        v-for="(message, index) in dataList" 
        :key="index" 
        :class="['message', message.isOwn ? 'own-message' : 'other-message']"
      >
        <div class="message-content-wrapper">
          <div v-if="!message.isOwn" class="user-info">
            <div class="avatar">{{ message.CreateName?.substring(0, 1) || 'U' }}</div>
            <div class="username">{{ message.CreateName || 'Unknown User' }}</div>
          </div>
          
          <div class="message-content">
            <div class="text-content" v-if="message.contentDesc">
              {{ message.contentDesc }}
            </div>
            
            <div class="image-content" v-if="message.contentUrl">
              <ImagePreview :src="message.contentUrl" />
            </div>
            
            <div class="message-time">
              {{ formatTime(message.createTime) }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input-area">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="contentDesc" >
          <el-input style="width: 50%;"
            v-model="form.contentDesc"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容..."
            
          />
                <el-form-item prop="contentUrl" style="width: 30%;">
          <UploadImage v-model="form.contentUrl" :data="{ uploadType: 1 }" />
        </el-form-item>
    
        
        <el-form-item style="width: 20%;">
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="state.submitLoading"
          >
            发送
          </el-button>
          <el-button @click="reset">取消</el-button>
        </el-form-item>
        </el-form-item>
      
      </el-form>
    </div>
  </div>
</template>

<script setup name="egfeedbacklist">
import { listEgFeedbackList, addEgFeedbackList, delEgFeedbackList, updateEgFeedbackList, getEgFeedbackList } from '@/api/buss/egfeedbacklist.js'

import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance()
const ids = ref([])
const loading = ref(false)
const showSearch = ref(true)
const queryParams = reactive({
  feedbackID: '',
  pageNum: 1,
  pageSize: 100, // Increase page size for chat view
  sort: 'createTime',
  sortType: 'asc',
})
const route = useRoute()
const userInfo = computed(() => {
  return useUserStore().userInfo
})
watch(
  () => route.query.feedbackID,
  (val) => {
    if (val) { 
      getList(val)
    }
  },
  {
    immediate: true
  }
)
const columns = ref([
  { visible: true, align: 'center', type: '', prop: 'feedbackID', label: '售后编号', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'contentName', label: '发言人', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'contentDesc', label: '内容描述', showOverflowTooltip: true },
  { visible: true, align: 'center', type: 'img', prop: 'contentUrl', label: '内容附件', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'createTime', label: 'CreateTime', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'createName', label: 'CreateName', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'def', label: 'Def', showOverflowTooltip: true },
  { visible: true, align: 'center', type: '', prop: 'sourceForm', label: 'SourceForm', showOverflowTooltip: true },
])

const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])

var dictParams = []

// Format time for display
function formatTime(timeString) {
  if (!timeString) return ''
  const date = new Date(timeString)
  return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

function getList(feedbackID) {
  loading.value = true 
    queryParams.feedbackID = feedbackID;
  listEgFeedbackList(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      // Add isOwn property to distinguish own messages
      dataList.value = data.result.map(item => ({
        ...item,
        isOwn: item.createName === userInfo.value.userName // Replace 'CurrentUser' with actual current user identifier
      }))
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// Query
function handleQuery() {
  queryParams.pageNum = 1
  queryParams.feedbackID = route.query.feedbackID || ''
  getList()
}

// Reset query
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// Custom sorting
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order
  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form operations ***************/
const formRef = ref()
const title = ref('')
// Operation type 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  single: true,
  multiple: true,
  submitLoading: false,
  form: {},
  rules: {
    contentDesc: [{ required: true, message: "消息内容不能为空", trigger: "blur" }],
  },
  options: {}
})

const { form, rules, options, single, multiple } = toRefs(state)

// Close dialog
function cancel() {
  open.value = false
  reset()
}

// Reset form
function reset() {
  form.value = {
    feedbackID: null,
    contentName: null,
    contentDesc: null,
    contentUrl: null,
    createTime: null,
    createName: null,
    def: null,
    sourceForm: null,
  };
  proxy.resetForm("formRef")
}

// Add button operation
function handleAdd() {
  reset();
  open.value = true
  state.submitLoading = false
  title.value = '添加'
  opertype.value = 1
}

// Modify button operation
function handleUpdate(row) {
  reset()
  const id = row.feedbackID || ids.value
  getEgFeedbackList(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = '修改'
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// Add & modify form submission
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      state.submitLoading = true
      form.value.feedbackID = route.query.feedbackID || '';
      // Set current user name before sending
      form.value.contentName = ''; // Replace with actual current user identifier
      form.value.createTime = new Date().toISOString();

      addEgFeedbackList(form.value).then((res) => {
        proxy.$modal.msgSuccess("发送成功")
        reset()
        getList()
      })
      .finally(() => {
        setTimeout(() => {
          state.submitLoading = false
        }, 800)
      })
    }
  })
}

// Delete button operation
function handleDelete(row) {
  const Ids = row.feedbackID || ids.value

  proxy
    .$confirm('是否确认删除参数编号为"' + Ids + '"的数据项？', "警告", {
      confirmButtonText: proxy.$t('common.ok'),
      cancelButtonText: proxy.$t('common.cancel'),
      type: "warning",
    })
    .then(function () {
      return delEgFeedbackList(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
}

handleQuery()
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px);
  background-color: #f5f5f5;
  padding: 15px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message {
  display: flex;
  max-width: 80%;
}

.other-message {
  align-self: flex-start;
}

.own-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message-content-wrapper {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.other-message .message-content-wrapper {
  flex-direction: row;
}

.own-message .message-content-wrapper {
  flex-direction: row-reverse;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 50px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 5px;
}

.username {
  font-size: 12px;
  color: #999;
  text-align: center;
  word-break: break-all;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.text-content {
  background-color: white;
  padding: 10px 15px;
  border-radius: 18px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  word-wrap: break-word;
  max-width: 400px;
}

.own-message .text-content {
  background-color: #409eff;
  color: white;
  border-bottom-right-radius: 4px;
}

.other-message .text-content {
  background-color: white;
  border-bottom-left-radius: 4px;
}

.image-content {
  max-width: 300px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-time {
  font-size: 12px;
  color: #999;
  align-self: flex-end;
}

.chat-input-area {
  background-color: white;
  padding: 15px;
  border-top: 1px solid #eaeaea;
  border-radius: 10px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.chat-input-area .el-form-item {
  margin-bottom: 15px;
}
</style>